package com.sh.secondhand;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.*;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.qiniu.android.utils.StringUtils;
import com.sh.Application.BaseApplication;
import com.sh.struts.GlobalDefine;
import com.sh.struts.ProductData;
import com.sh.utils.CommonStringUtils;
import com.sh.utils.Http.OkHttpUtils;
import com.sh.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import static com.sh.struts.GlobalDefine.BACKGROUND_MANAGER_DOMAIN;

public class ProductDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ProductDetailActivity";
    private static final String OPEN_WEBVIEW = "%s/app/webview_product_detail/?product_id=%s";
    private String re_user = "";
    private String re_username = "";
    private String re_comment_id = "";
    private Integer productId = 0;
    private Map<Boolean,Integer> collectIconMap = new HashMap<Boolean, Integer>(){{
        put(true,R.mipmap.cancel_collect);
        put(false,R.mipmap.collect);
    }};


    private InputMethodManager imm;


    @BindView(R.id.pro_webview)
    WebView proWebview;

    @BindView(R.id.comment)
    RelativeLayout showComment;
    @BindView(R.id.collect)
    RelativeLayout collect;
    @BindView(R.id.want_buy_btn)
    Button wantBuy;
    @BindView(R.id.web_view_relative)
    RelativeLayout webViewRelative;
    @BindView(R.id.comment_input)
    EditText commentInput;
    @BindView(R.id.coment_send)
    Button sendComment;
    @BindView(R.id.show_comment_view)
    LinearLayout showCommentView;
    @BindView(R.id.hidden_comment_view)
    LinearLayout hideCommentView;
    @BindView(R.id.imageView3)
    SimpleDraweeView simpleDraweeView;
    @BindView(R.id.comment_user_img)
    SimpleDraweeView simpleDraweeViewshow;
    @BindView(R.id.imageView4)
    ImageView collectIcon;
    @BindView(R.id.invalid_view)
    LinearLayout invalidView;

    private boolean isComment = false;
    private boolean isCollected = false;
    private boolean coolectLock = false;
    private ProductData productData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        productData = (ProductData) intent.getSerializableExtra("product_data");
        productId = productData == null ? 0 : productData.productId;
        isCollected = productData == null ? false : productData.isCollected;
        if(Utils.checkLogin()){
            if(productData != null && productData.userId.equals(BaseApplication.getLoginInfo().getUserId())){
                wantBuy.setVisibility(View.GONE);
            }
        }
        initCollectStatus(productId);
        webViewConfig(proWebview);
        proWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        proWebview.loadUrl(String.format(OPEN_WEBVIEW, GlobalDefine.BACKGROUND_MANAGER_DOMAIN, productId));
        proWebview.addJavascriptInterface(this, "android");
        commentInput.setFocusable(true);
        commentInput.setFocusableInTouchMode(true);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        simpleDraweeView.setImageURI(BaseApplication.getLoginInfo() != null ? BaseApplication.getLoginInfo().getUserImgUrl() : null);
        simpleDraweeViewshow.setImageURI(BaseApplication.getLoginInfo() != null ? BaseApplication.getLoginInfo().getUserImgUrl() : null);
        if(!productData.isValid){
            showCommentView.setVisibility(View.GONE);
            hideCommentView.setVisibility(View.GONE);
            invalidView.setVisibility(View.VISIBLE);
        }
    }

    private void webViewConfig(WebView webView) {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

        //支持插件
        //webSettings.setPluginsEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        //优先使用缓存:
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据
    }

    /**
     * 显示评论输入框
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void showCommentView(String user_id, String username, String recomment_id) {
        if (Utils.checkLogin()) {
            if(productData.isValid) {
                re_user = user_id;
                re_username = username;
                re_comment_id = recomment_id;
                runOnUiThread(() -> {
                    hideCommentView.setVisibility(View.GONE);
                    showCommentView.setVisibility(View.VISIBLE);
                    isComment = true;
                    commentInput.requestFocus();
                    if (!StringUtils.isNullOrEmpty(user_id) && !StringUtils.isNullOrEmpty(username)) {
                        commentInput.setHint("回复 " + username);
                    }
                    if (imm != null) {
                        imm.showSoftInput(commentInput, 0);
                    }
                });
            }
        } else {
            showToastOnThread(ProductDetailActivity.this, "请登录后再评论");
        }
    }

    /**
     * 显示正常情况下的底栏
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void hideCommentView() {
        runOnUiThread(() -> {
            re_user = "";
            re_username = "";
            re_comment_id = "";
            if (imm != null) {
                imm.hideSoftInputFromWindow(commentInput.getWindowToken(), 0);
            }
            showCommentView.setVisibility(View.GONE);
            hideCommentView.setVisibility(View.VISIBLE);
            commentInput.setText("");
            isComment = false;
        });
    }

    /**
     * 在子线程里需要使用Toast
     *
     * @param context
     * @param message
     */
    public void showToastOnThread(Context context, String message) {
        runOnUiThread(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT).show());
    }

    @OnClick({R.id.comment, R.id.web_view_relative, R.id.pro_webview, R.id.coment_send, R.id.collect,R.id.want_buy_btn})
    @Override
    public void onClick(View v) {
        Integer id = v.getId();
        switch (id) {
            case R.id.comment: {
                showCommentView("", "", "");
                break;
            }
            case R.id.web_view_relative: {
                if (isComment) {
                    hideCommentView();
                }
                break;
            }
            case R.id.pro_webview: {
                if (isComment) {
                    hideCommentView();
                }
                break;
            }
            case R.id.coment_send: {
                String comment = commentInput.getText().toString();
                if (StringUtils.isNullOrEmpty(comment)) {
                    commentInput.setError("内容不能为空");
                    commentInput.requestFocus();
                } else {
                    if (Build.VERSION.SDK_INT < 18) {
                        proWebview.post(() -> {
                            // 注意调用的JS方法名要对应上
                            // 调用javascript的callJS()方法
                            proWebview.loadUrl("javascript:add_comment('" + BaseApplication.getLoginInfo().getUserId() + "','" + comment + "','" + re_comment_id + "')");
                            hideCommentView();
                        });
                    } else {
                        proWebview.evaluateJavascript("javascript:add_comment('" + BaseApplication.getLoginInfo().getUserId() + "','" + comment + "','" + re_comment_id + "')",
                            value -> {
                                hideCommentView();
                            });
                    }
                }
                break;
            }
            case R.id.collect: {
                if(Utils.checkLogin()){
                    if(coolectLock) {
                        Integer userId = BaseApplication.getLoginInfo().getUserId();
                        collect(userId, productId, isCollected ? 0 : 1);
                    }
                }else{
                    showToastOnThread(ProductDetailActivity.this,"请先登录之后再收藏！");
                }
                break;
            }
            case R.id.want_buy_btn:{
                if(Utils.checkLogin()) {
                    Intent intent = new Intent(ProductDetailActivity.this,ReadyCreateOrderActivity.class);
                    intent.putExtra("product_data",productData);
                    startActivity(intent);
                }else{
                    showToastOnThread(ProductDetailActivity.this,"登录之后才能购买哦！");
                }
                break;
            }
        }
    }

    @JavascriptInterface
    public void webViewReload(){
         proWebview.post(() -> {
            proWebview.reload();
        });
    }

    public void collect(Integer user_id,Integer product_id,Integer is_collect){
        boolean collect = is_collect != null && is_collect != 0 ? true : false;
        isCollected = collect;
        collectIcon.setImageResource(collectIconMap.get(collect));
        String url = String.format("%s/app/collect_product/?user_id=%s&product_id=%s&is_collect=%s",BACKGROUND_MANAGER_DOMAIN,user_id,product_id,is_collect);
        OkHttpUtils.get(url, new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                if("error".equals(response)){
                    showToastOnThread(ProductDetailActivity.this,"操作失败");
                    runOnUiThread(()->collectIcon.setImageResource(collectIconMap.get(!collect)));
                    isCollected = !collect;
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastOnThread(ProductDetailActivity.this,"操作失败，请检查网络后重试~");
                runOnUiThread(()->collectIcon.setImageResource(collectIconMap.get(!collect)));
                isCollected = !collect;
            }
        });
    }

    public void initCollectStatus(Integer product_id) {
        if (Utils.checkLogin()) {
            Integer user_id = BaseApplication.getLoginInfo().getUserId();
            String url = String.format("%s/app/get_product_info_by_id/?user_id=%s&product_id=%s", BACKGROUND_MANAGER_DOMAIN, user_id, product_id);
            OkHttpUtils.get(url, new OkHttpUtils.ResultCallback<String>() {
                @Override
                public void onSuccess(String response) {
                    if (!StringUtils.isNullOrEmpty(response)) {
                        Map<String, String> resMap = new Gson().fromJson(response, Map.class);
                        isCollected = CommonStringUtils.safeInteger(resMap.get("is_collected")) == 0 ? false : true;
                        runOnUiThread(() -> collectIcon.setImageResource(collectIconMap.get(isCollected)));
                    }
                    coolectLock = true;
                }

                @Override
                public void onFailure(Exception e) {
                    coolectLock = true;
                }
            });
        }
        coolectLock = true;
    }
}
